<template>
	<div v-if="!renew">
		<el-table :data="data" style="width: 100%;height: auto;" empty-text="尚未标准化！" v-loading="loading"
			element-loading-text="正在标准化中...">
			<el-table-column prop="origin" label="原始字段" />
			<el-table-column prop="standard" label="标准化字段" />
		</el-table>
		<div style="margin-top: 20px;">
			<el-select v-model="standerd" placeholder="选择对齐标准">
				<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
			</el-select>
			<el-button type="primary" style="margin-left: 20px;" @click="onStandardization">
				{{ button_text }}</el-button>
		</div>
		<div style="color:grey;font-size:small;position: relative;top:12px;" v-if="standard_time">
			上次标准化时间:{{ standard_time }}</div>
	</div>
	<div v-else>
		<el-table :data="result" style="width: 100%;height: auto;" v-if="renew">
			<el-table-column prop="origin" label="原始字段" width="180" />
			<el-table-column prop="options" label="标准字段候选:匹配概率" width="300">
				<template #default="scope">
					<el-select v-model="scope.row.final" placeholder="请确定标准化字段" style="width: 100%;">
						<el-option v-for="item in scope.row.options" :label="item" :value="item.split(':')[0]" />
					</el-select>
				</template>
			</el-table-column>
			<el-table-column label="查看示例数据">
				<template #default="scope">
					<el-tooltip placement="right">
						<template #content>
							<div v-for="(item, index) in scope.row.example" :key="index">
								{{ item }}
							</div>
						</template>
						<el-button type="primary" :icon="Search" circle />
					</el-tooltip>
				</template>
			</el-table-column>
			<el-table-column prop="options" label="自定标准化字段" width="300">
				<template #default="scope">
					<el-autocomplete v-model="scope.row.diy" :fetch-suggestions="querySearch" clearable style="width: 100%;"
						placeholder="自定字段" />
				</template>
			</el-table-column>
		</el-table>
		<el-button type="primary" style="margin-top: 20px;" @click="onSave">保存</el-button>
		<el-button style="margin-top: 20px;" @click="renew = !renew">取消</el-button>
	</div>
</template>
  
<script setup>
import { onMounted, ref, reactive } from 'vue'
import { useDatabase } from '@/stores/databaseStore'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Success } from '../../util/message'
import Api from '../../util/axios'
import { Search } from '@element-plus/icons-vue'

const renew = ref(false)
const data = reactive([])
const button_text = ref('')
const route = useRoute()
const database = useDatabase()
const standard_time = ref('')
const select_list = reactive([])
const standerd = ref('')
const options = [
	{
		value: 'Option1',
		label: '北京',
	},
	{
		value: 'Option2',
		label: '上海',
	},
	{
		value: 'Option3',
		label: '天津',
	},
	{
		value: 'Option4',
		label: '浙江',
	},
	{
		value: 'Option5',
		label: '江苏',
	}
]
let table = ''
onMounted(async () => {
	Api.post('/get_lable').then((res) => {
		res.forEach(element => {
			select_list.push({ value: element })
		});
	})
	table = route.query.table
	if (!Object.keys(database.raw).length) {
		useRouter().push({ name: 'database' })
	}
	button_text.value = database.raw[table].standar == '1' ? '重新标准化' : '开始标准化'
	standard_time.value = database.raw[table].standar == '1' ? database.raw[table].standard_time : ''
	for (let key in database.raw[table].columns_res) {
		data.push({ origin: key, standard: database.raw[table].columns_res[key] })
	}
})

const result = reactive([])
let time
const loading = ref(false)
const onStandardization = () => {
	ElMessageBox.confirm(
		'是否确定重新标准化该表？',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(async () => {
			loading.value = true
			await Api.post('standardize', {
				"dbname": database.name,
				"tablename": table
			}).then((res) => {
				let example = res.example
				result.length = 0
				for (const key in res.result) {
					let options = []
					for (let i = 0; i < res.result[key].length; i += 2) {
						options.push(res.result[key][i] + ":" + res.result[key][i + 1])
					}
					result.push({ origin: key, options: options, example: example[key], final: options[0].split(':')[0], diy: '' })
				}
				time = res['standard_time']
			})
			Success('标准化完成，请选择匹配结果')
			loading.value = false
			renew.value = !renew.value
		})
}

const querySearch = (queryString, cb) => {
	const createFilter = (queryString) => {
		return (item) => {
			return (
				item.value.indexOf(queryString) != -1
			)
		}
	}
	const results = queryString
		? select_list.filter(createFilter(queryString))
		: select_list
	// call callback function to return suggestions
	cb(results)
}
const onSave = async () => {
	let mappings = {}
	let optimize = false
	for (let index in result) {
		mappings[result[index].origin] = result[index].diy ? result[index].diy : result[index].final
		if (result[index].diy || result[index].options[0].split(':')[0] != result[index].final) {
			optimize = true
		}
	}
	if (optimize) {
		optimize = false
		await ElMessageBox.confirm(
			'选择的字段非推荐可能性最高字段，是否将该结果作为模型优化数据？',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				optimize: optimize
			}).then(() => {
				optimize = true
			}).catch(() => { optimize = false })
	}
	Api.post('renew_map', {
		"dbname": database.name,
		"table_name": table,
		"result": mappings,
		'standard_time': time,
		"optimize": optimize
	}).then(res => {
		if (res.msg == 'success') {
			database.raw[table].columns_res = mappings
			database.raw[table].standard_time = time
			data.length = 0
			for (let key in mappings) {
				data.push({ origin: key, standard: mappings[key] })
			}
			Success('保存成功')
			renew.value = !renew.value
		}
	})
}
</script>